package com.example.tablefield.config;

import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.lang.reflect.Field;

@Configuration
public class JacksonConfig {

    @PostConstruct
    public void initMyBatisPlusJacksonTypeHandler() throws Exception{
        // 将我们自定义的、支持多态的ObjectMapper设置给MyBatis-Plus的JacksonTypeHandler
        // 通过反射获取私有静态属性
        Field field = JacksonTypeHandler.class.getDeclaredField("objectMapper");
        // 取消访问检查
        field.setAccessible(true);
        // 修改属性值
        field.set(null, objectMapper());  // 静态属性的set参数传null
    }

    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();

        // 关键配置：启用默认的类型信息，用于处理多态性
        objectMapper.activateDefaultTyping(
                LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT, // 其它几个参数，试了有问题
                JsonTypeInfo.As.PROPERTY // 默认属性名是 @class
        );

        return objectMapper;
    }
}